package com.springcloud.auth.scheduled;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springcloud.auth.config.OauthConfig;
import com.springcloud.auth.entity.TToken;
import com.springcloud.auth.service.TTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 定时任务，用于清理数据库中过期的token
 * 
 * @author hzl
 *
 */
@Component
public class OauthScheduledService {

	private static final Logger logger = LoggerFactory.getLogger(OauthScheduledService.class);
	
	@Resource
	private TTokenService tokenService;

	/**
	 * 可以设置轮询的时间,此处设置为15分钟清除一次
	 */
	@Scheduled(cron = "0 0/15 * ? * *")
	public void scheduled() {
		logger.info("========轮询token表，清除数据======");
		Date now = new Date();
		long expire = now.getTime() - OauthConfig.REFRESH_TOKEN_EXPIRE * 1000;

		QueryWrapper<TToken> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().le(TToken::getRefreshUpdateTime,new Date(expire));

		//现在的时间往后倒退refresh过期的时间，就是需要清楚数据的条件
		tokenService.remove(queryWrapper);

		logger.info("========轮询结束======");
	}
}
